<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Custom as ModelCustom;
use app\common\model\shop\Order;

/**
 * 客户接口
 */
class Custom extends Api
{
    protected $noNeedLogin = ['info'];
    protected $noNeedRight = ['*'];

    /**
     * 新增/编辑客户
     * @ApiMethod (POST)
     * @param int  $id  客户id（编辑必填）
     * @param string $name  客户名称
     * @param string $phone  联系方式
     * @param string $city  省市区
     * @param string $address  详细地址
     * @param string $province_id  省ID
     * @param string $city_id  市ID
     * @param string $area_id  区ID
     */
    public function add_edit()
    {
        $param = request()->param();
        extract($param);
        $param['user_id'] = $this->auth->id;
        $city = explode('/', $city);
        if (!isset($param['province_id']) || !$param['province_id']) {
            $provinceinfo = db('cnarea')->whereLike('short_name|name', '%' . $city[0] . '%')->where('level', 1)->find();
            if (!$provinceinfo) {
                $this->error('省错误');
            }
            $param['province_id'] = $provinceinfo['area_code'];
        }
        if (!isset($param['city_id']) || !$param['city_id']) {
            $cityinfo = db('cnarea')->whereLike('short_name|name', '%' . $city[1] . '%')->where('parent_code', $provinceinfo['area_code'])->where('level', 2)->find();
            if (!$cityinfo) {
                $this->error('市错误');
            }
            $param['city_id'] = $cityinfo['area_code'];
        }
        if (!isset($param['area_id']) || !$param['area_id']) {
            $areainfo = db('cnarea')->whereLike('short_name|name', '%' . $city[2] . '%')->where('parent_code', $cityinfo['area_code'])->where('level', 3)->find();
            if (!$areainfo) {
                $this->error('区错误');
            }
            $param['area_id'] = $areainfo['area_code'];
        }
        if (isset($param['id']) && $param['id']) {
            $has = ModelCustom::where('phone', $param['phone'])->where('id', '<>', $param['id'])->find();
            if ($has) {
                $this->error('该客户已存在');
            }
            $custom = new ModelCustom();
            $res = $custom->isUpdate(true)->allowField(true)->save($param);
        } else {
            $param['acct_id'] = $this->auth->getUser()->acct_id ?? 0;
            $custom = new ModelCustom($param);
            $has = ModelCustom::where('phone', $param['phone'])->find();
            if ($has) {
                $this->error('该客户已存在');
            }
            $res = $custom->isUpdate(false)->allowField(true)->save();
            $day = config('site.del_custom_day');
            queue('app\common\job\DelCustom', $custom->id, $day * 86400, 'del_custom1243');
        }
        if ($res) {
            $this->success('成功', $custom);
        } else {
            $this->error('失败');
        }
    }
    /**
     * 删除客户
     * @ApiMethod (POST)
     * @param int  $id  客户id
     */
    public function del()
    {
        $param = request()->param();
        extract($param);
        if (!isset($id) || !$id) {
            $this->error('参数错误');
        }
        $custom = ModelCustom::get($id);
        if ($custom) {
            $res = $custom->delete();
            if ($res) {
                $this->success('成功');
            }
        }
        $this->error('失败');
    }

    /**
     * 客户列表
     * @ApiMethod (GET)
     */
    public function lists()
    {
        $param = request()->param();
        extract($param);
        $custom = new ModelCustom;
        if (isset($keywords) && $keywords) {
            $custom->whereLike('fa_custom.name|fa_custom.phone', '%' . $keywords . '%');
        }
        $days = config('site.del_custom_day') ?? 90;
        $less = $days * 86400;
        $now = time();
        $list = $custom->where('user_id', $this->auth->id)
            ->field("fa_custom.*")
            ->group('fa_custom.id')
            // ->order('less_day_del desc')
            ->paginate();
        foreach ($list as $k => $v) {
            if (is_null($v->lasttime)) {
                $v->less_day_del = ceil(($v->createtime + $less - $now) / 86400);
            } else {
                $v->less_day_del = ceil(($v->lasttime + $less - $now) / 86400);
            }
        }
        $this->success('', $list);
    }

    /**
     * 客户详情
     * @ApiMethod (GET)
     */
    public function info()
    {
        $param = request()->param();
        extract($param);
        if (!isset($id) || !$id) {
            $this->error('参数错误');
        }
        $data = ModelCustom::get($id);
        $this->success('', $data);
    }

    /**
     * 客户订单列表
     * @ApiMethod (GET)
     * @param int  $id  客户id
     * @param int  $status  订单状态:0=待审核,1=运输中,99=成功
     * 
     */
    public function order_list()
    {
        $param = request()->param();
        extract($param);
        if (!isset($id) || !$id || !isset($status)) {
            $this->error('参数错误');
        }
        $list = Order::with('ordergoods')->where('status', $status)->where('custom_id', $id)->order('id', 'desc')->paginate();
        $this->success('', $list);
    }
}
